package com.example.administrator.base.activity;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.erebus.blelocklibrary.config.Config;
import com.erebus.blelocklibrary.config.LockType;
import com.erebus.blelocklibrary.impl.AndroidBle;
import com.erebus.blelocklibrary.inter.IBLE;
import com.erebus.blelocklibrary.inter.OnConnectionListener;
import com.erebus.blelocklibrary.inter.OnDeviceSearchListener;
import com.erebus.blelocklibrary.utils.ConvertUtils;
import com.erebus.blelocklibrary.utils.GlobalParameterUtils;
import com.example.administrator.base.R;
import com.example.administrator.base.util.AppManager;
import com.example.administrator.base.util.BLEStringUtils;
import com.example.administrator.base.util.HexUtils;
import com.example.administrator.base.util.MPermissionsActivity;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;



public class LockManageActivity extends MPermissionsActivity implements OnConnectionListener {
    @InjectView(R.id.tv_name)
    TextView tvName;
    @InjectView(R.id.tv_address)
    TextView tvAddress;
    @InjectView(R.id.tv_status)
    TextView tvStatus;
    @InjectView(R.id.tv_version)
    TextView tvVersion;
    @InjectView(R.id.tv_battery)
    TextView tvBattery;
    @InjectView(R.id.tv_cz)
    TextView tvCz;
    @InjectView(R.id.tv_gsm)
    TextView tvGsm;
    @InjectView(R.id.tv_work_status)
    TextView tvWorkStatus;
    @InjectView(R.id.bt_gsm)
    Button btGsm;
    @InjectView(R.id.bt_work)
    Button btWork;
    @InjectView(R.id.tv_mode)
    TextView tvMode;
    @InjectView(R.id.bt_query)
    Button btQuery;
    @InjectView(R.id.Toolbar)
    android.support.v7.widget.Toolbar Toolbar;
    @InjectView(R.id.bt_setmode)
    Button btSetmode;
    @InjectView(R.id.bt_nomal)
    Button btNomal;
    private int bleStatus;

    private String address;
    private String password;
    private String key;
    private ProgressDialog loadingDialog;
    private int selectMode = -1;
    private StringBuffer stringBuffer;
    String response;
    private IBLE ible;
    SweetAlertDialog sweetAlertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_lock_manage);
        ButterKnife.inject(this);
        AppManager.getAppManager().addActivity(this);
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setCanceledOnTouchOutside(false);
        sweetAlertDialog.setTitleText("加载中");
        Toolbar.setTitle("赳猎人");
        Toolbar.setSubtitle("车锁详情");
        bleStatus = 0;
        setSupportActionBar(Toolbar);
        Toolbar.setNavigationIcon(R.drawable.backbar);
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ible = new AndroidBle(this);
        ButterKnife.inject(this);
        registerReceiver(broadcastReceiver, Config.initFilter());
        Intent intent = getIntent();
        address = intent.getStringExtra("mac");
        password = intent.getStringExtra("password");
        key = intent.getStringExtra("key");
        stringBuffer = new StringBuffer();
        GlobalParameterUtils.getInstance().setLockType(LockType.MTS);
        response = intent.getStringExtra("re");
        Log.i("3378565454", response);
        Message message = new Message();
        message.what = 4;
        message.obj = response;
        m_myHandler.sendMessage(message);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
        ible.close();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
            broadcastReceiver = null;
        }

        m_myHandler.removeCallbacksAndMessages(null);
      /*  Process.killProcess(Process.myPid());*/
    }


    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String data = intent.getStringExtra("data");
            switch (action) {
                case Config.TOKEN_ACTION:
                    m_myHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ible.getBattery();
                        }
                    }, 300);
                    tvVersion.setText(getString(R.string.nowcodevesion,GlobalParameterUtils.getInstance().getVersion()));
                    break;
                case Config.BATTERY_ACTION:
                    if (TextUtils.isEmpty(data)) {
                        tvCz.setText("当前操作：获取电量失败");
                    } else {
                        tvCz.setText("当前操作：获取电量成功");
                        tvBattery.setText(getString(R.string.nowv,Integer.parseInt(data, 16)));
                        m_myHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ible.getLockStatus();
                            }
                        }, 300);
                    }
                    break;
                case Config.OPEN_ACTION:
                    if (TextUtils.isEmpty(data)) {
                        tvCz.setText("当前操作：开锁失败");
                    } else {
                        tvCz.setText("当前操作：开锁成功");
//                        update();
                    }
                    break;
                case Config.CLOSE_ACTION:
                    if (TextUtils.isEmpty(data)) {
                        tvCz.setText("当前操作：复位失败");
                    } else {
                        tvCz.setText("当前操作：复位成功");
                    }
                    break;
                case Config.LOCK_STATUS_ACTION:
                    if (TextUtils.isEmpty(data)) {
                        tvCz.setText("当前操作：锁已关闭");
                        m_myHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                               /* getIBLE().openLock();*/
                            }
                        }, 300);

                    } else {
                        tvCz.setText("当前操作：锁已开启");

                    }
                    break;
                case Config.LOCK_RESULT:
                    if (TextUtils.isEmpty(data)) {
                        tvCz.setText("当前操作：上锁超时");
                    } else {
                        tvCz.setText("当前操作：上锁成功");
                    }
                    break;
                case Config.SET_MODE:
                    if (TextUtils.isEmpty(data)) {
                        switch (selectMode) {
                            case 0:
                                tvCz.setText("当前操作：设置正常模式失败");
                                break;
                            case 1:
                                tvCz.setText("当前操作：设置运输模式失败");
                                break;
                            case 2:
                                tvCz.setText("当前操作：设置重启模式失败");
                                break;
                        }
                    } else {
                        switch (selectMode) {
                            case 0:
                                tvCz.setText("当前操作：设置正常模式成功");
                                break;
                            case 1:
                                tvCz.setText("当前操作：设置运输模式成功");
                                break;
                            case 2:
                                tvCz.setText("当前操作：设置重启模式成功");
                                break;
                        }
                    }
                    break;
                case Config.GEt_LOCK_WORK_STATUS:

                    if (!TextUtils.isEmpty(data) && data.length() % 2 == 0) {
                        stringBuffer.setLength(0);
                        byte[] bytes = ConvertUtils.hexString2Bytes(data);
                        String tString = Integer.toBinaryString((bytes[3] & 0xFF) + 0x100).substring(1);
                        String lockStatus = tString.substring(tString.length() - 1, tString.length()).equals("0") ? "开" : "关";
                        String zd = tString.substring(tString.length() - 2, tString.length() - 1).equals("0") ? "正常" : "故障";
                        String zdStatus = tString.substring(tString.length() - 3, tString.length() - 2).equals("0") ? "静止" : "振动";
                        String cdStatus = tString.substring(tString.length() - 4, tString.length() - 3).equals("0") ? "放电" : "充电";
                        stringBuffer.append("工作状态：\n锁状态：").append(lockStatus).append("\n振动功能：").append(zd).append("\n振动状态：").append(zdStatus).append("\n充放电状态：").append(cdStatus);
                        int r2 = Integer.parseInt(data.substring(8, 10), 16);
                        stringBuffer.append("\n电量：").append(r2);
                        int r3 = Integer.parseInt(data.substring(10, 12), 16);
                        switch (r3) {
                            case 0:
                                stringBuffer.append("\nGSM状态：关电状态");
                                break;
                            case 1:
                                stringBuffer.append("\nGSM状态：查询SIM卡");
                                break;
                            case 2:
                                stringBuffer.append("\nGSM状态：注册网络");
                                break;
                            case 3:
                                stringBuffer.append("\nGSM状态：初始化短信功能");
                                break;
                            case 4:
                                stringBuffer.append("\nGSM状态：查询GPRS网络");
                                break;
                            case 5:
                                stringBuffer.append("\nGSM状态：链接PPP");
                                break;
                            case 6:
                                stringBuffer.append("\nGSM状态：链接TCP");
                                break;
                            case 7:
                                stringBuffer.append("\nGSM状态：与平台通讯成功");
                                break;
                            case 254:
                                stringBuffer.append("\nGSM状态：已上电");
                                break;
                            case 255:
                                stringBuffer.append("\nGSM状态：故障");
                                break;
                        }
                        int r4 = Integer.parseInt(data.substring(12, 14), 16);
                        int r5 = Integer.parseInt(data.substring(14, 16), 16);
                        stringBuffer.append("\n上一次GPRS上线时间:").append(r4).append("\n上一次GSM信号强度:").append(r5);
                        int r6 = Integer.parseInt(data.substring(16, 18), 16);
                        switch (r6) {
                            case 0:
                                stringBuffer.append("\nGPS状态：关电状态");
                                break;
                            case 1:
                                stringBuffer.append("\nGPS状态：未定位");
                                break;
                            case 2:
                                stringBuffer.append("\nGPS状态：已定位");
                                break;
                            case 255:
                                stringBuffer.append("\nGPS状态：故障");
                                break;
                        }
                        int r7 = Integer.parseInt(data.substring(18, 20), 16);
                        int r8 = Integer.parseInt(data.substring(20, 22), 16);
                        stringBuffer.append("\n上一次GPS定位时间：").append(r7).append("\n上一次GPS收星数量：").append(r8);
                        tvWorkStatus.setText(stringBuffer.toString());

                    }
                    break;
                case Config.GSM_ID_ACTION:
                    if (!TextUtils.isEmpty(data)) {
                        tvGsm.setText("");
                        tvGsm.setText(getString(R.string.gsmid,data));
                        ible.getGSMVersion();
                    }
                    break;
                case Config.GSM_VERSION_ACTION:

                    if (!TextUtils.isEmpty(data)) {
                        Log.i("54415212", "" + data);
                        Log.i("54415212", "" + HexUtils.hexStr2Str(data));
                        tvGsm.append("\nGSM版本：" + HexUtils.hexStr2Str(data));
                    }
                    break;
                case Config.GET_MODE:
                    tvCz.setText("当前操作：获取工作模式成功");
                    if (TextUtils.isEmpty(data)) {
                        tvMode.setText("工作模式：运输模式");
                    } else {
                        tvMode.setText("工作模式：正常模式");
                    }
                    break;
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                    switch (state) {
                        case BluetoothAdapter.STATE_OFF:

                            break;
                        case BluetoothAdapter.STATE_ON:
//                            m_myHandler.sendEmptyMessageDelayed(0, 3000);
                            break;
                    }
                    break;
            }
        }
    };

    @Override
    public void onConnect() {

    }

    @Override
    public void onDisconnect(int state) {
        tvAddress.setText(getString(R.string.mac,""));
        tvName.setText("锁名：");
        tvStatus.setText("连接状态:未连接");
        tvBattery.setText("当前电量：");
        tvCz.setText("当前操作：");
        tvVersion.setText("当前版本：");
        Toast.makeText(LockManageActivity.this, "连接失败", Toast.LENGTH_LONG).show();
        if (null != loadingDialog && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

    @Override
    public void onServicesDiscovered(String name, String address) {
        Log.i("11354215", "蓝牙连接成功");
        Toast.makeText(LockManageActivity.this, "蓝牙连接成功", Toast.LENGTH_LONG).show();
        if (null != loadingDialog && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
        tvAddress.setText(getString(R.string.mac,address));
        tvName.setText(getString(R.string.lockname,name));
        tvStatus.setText("连接状态:已连接");
        tvVersion.setText("当前固件版本：");
        tvBattery.setText("当前电量：");
        tvCz.setText("当前操作：");
        getToken();
    }


    /**
     * 获取token
     */
    private void getToken() {
        m_myHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ible.getToken();
            }
        }, 1000);
    }


    @OnClick(R.id.bt_gsm)
    void setBtGsm() {
        ible.getGSMId();
    }

    @OnClick(R.id.bt_work)
    void setBtWork() {
        ible.getLockWorkStatus();
    }


    @OnClick(R.id.bt_reset)
    void reset() {
        ible.resetLock();
    }


    @OnClick(R.id.bt_query)
    void query() {
        ible.getMode();
    }

    @OnClick(R.id.bt_setmode)
    void setmode() {
        selectMode = 1;
        ible.setMode(selectMode);
    }
    @OnClick(R.id.bt_nomal)
    public void onViewClicked() {
        selectMode = 0;
        ible.setMode(selectMode);
    }

    Handler m_myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message mes) {
            switch (mes.what) {
                case 0:
                    ible.connect(address, LockManageActivity.this);
                    break;
                case 1:
                    break;
                case 2:
                    tvCz.setText("上传请求超时");
                    break;
                case 4:
                    String result = (String) mes.obj;
                    if (result.contains("失三点方发三个傻瓜败")) {
                        tvCz.setText("当前操作：查询失败");
                    } else {
                        Log.i("337854654", "fsd");
                        resetKey();
                    }
                    break;
            }
            return false;
        }
    });

    private byte[] getPassword(String passWord) {
        byte[] buf = new byte[passWord.length() / 2];
        for (int i = 0; i < buf.length; i++) {
            buf[i] = (byte) Integer.parseInt(passWord.substring(i * 2, i * 2 + 2));
        }
        return buf;
    }

    private byte[] getKey(String key) {
        byte[] buf = new byte[key.length() / 2];
        for (int i = 0; i < key.length() / 2; i++) {
            buf[i] = (byte) Integer.parseInt(key.substring(i * 2, i * 2 + 2));
        }
        return buf;
    }

    /**
     * 重置密钥密码
     */
    private void resetKey() {
        try {
            tvAddress.setText(getString(R.string.mac,""));
            tvName.setText("锁名：");
            tvStatus.setText("连接状态:已断开");
            tvCz.setText("当前操作：");
            tvBattery.setText("当前电量:");
            Config.key = getKey(key);
            Config.password = getPassword(password);
            final String mac = BLEStringUtils.encodeMAC(address);
           /* ible.connect(BLEStringUtils.encodeMAC(address), this);*/
            ible.startScan(new OnDeviceSearchListener() {
                @Override
                public void onScanDevice(final BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
                    if (bluetoothDevice == null || TextUtils.isEmpty(bluetoothDevice.getAddress()))
                        return;
                    String bluetoothMac = bluetoothDevice.getAddress();
                    if (mac.equalsIgnoreCase(bluetoothMac)) {
                        Log.d("3378451844154", "finded");
                        ible.stopScan();
                        bleStatus = 0;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ible.connectDevice(bluetoothDevice,LockManageActivity.this);
                            }
                        });
                    }

                }
            });
            bleStatus = 1;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!isFinishing() && ible.isEnable() && bleStatus == 1) {
                        ible.stopScan();
                        bleStatus = 0;
                        Toast.makeText(LockManageActivity.this, "连接超时", Toast.LENGTH_LONG).show();
                        loadingDialog.dismiss();
                        finish();

                    }
                }
            }, 15 * 1000);
            if (null == loadingDialog) {
                loadingDialog = ProgressDialog.show(this, "", "正在连接...");
            }
            loadingDialog.setCancelable(true);
        } catch (Exception e) {
            e.printStackTrace();
            tvCz.setText("当前操作：查询失败");
        }

    }
}
